/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package SecureUtil;

import java.security.MessageDigest;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 *
 * @author Gwang
 */
public class PBEHelper {
	
	
	
    public static SecretKey getPBEKey(String pswdHash, String salt) throws Exception{
        PBEKeySpec pbeKeySpec;
        //PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;
        String pwnsalt = pswdHash+salt;
        pbeKeySpec = new PBEKeySpec(pwnsalt.toCharArray());
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
        return pbeKey;
    }
    public static String generateSalt(){
        SecureRandom rand = new SecureRandom();
        byte[] saltbytes = new byte[2];
        rand.nextBytes(saltbytes);
        return HashHelper.HexString(saltbytes);
    }
    public static byte[] PBEencrypt(SecretKey pbeKey, byte[] in) throws Exception{
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        byte[] fakesalt = new byte[8];
        byte[] pbeKeyArray = pbeKey.getEncoded();
        for(int i=0; i<8; i++){
            fakesalt[i] = pbeKeyArray[i];
        }
        PBEParameterSpec paramSpec = new PBEParameterSpec(fakesalt,100);
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey,paramSpec);
        return pbeCipher.doFinal(in);
    }
    public static byte[] PBEdecrypt(SecretKey pbeKey, byte[] in) throws Exception{
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        byte[] fakesalt = new byte[8];
        byte[] pbeKeyArray = pbeKey.getEncoded();
        for(int i=0; i<8; i++){
            fakesalt[i] = pbeKeyArray[i];
        }
        PBEParameterSpec paramSpec = new PBEParameterSpec(fakesalt,100);
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey,paramSpec);
        return pbeCipher.doFinal(in);
    }
    public static String getPasswordHash(String password) throws Exception {
        return HashHelper.HexString(HashHelper.SHA1(password.getBytes()));
    	
    }
    

}
